#include "AudioTransportImpl.h"
#include "OutputParam.h"

AudioTransportImpl::AudioTransportImpl(void)
{
	m_midRecordedDataIsAvailable = 0;
	m_midNeedMorePlayData = 0;
}

AudioTransportImpl::~AudioTransportImpl(void)
{
}

bool AudioTransportImpl::init_jni(JNIEnv* env)
{
	bool result = false;

	do 
	{
		m_midRecordedDataIsAvailable = (env)->GetMethodID(m_cls, "recordedDataIsAvailable", "([BIBBIIIILcom/voe/common/OutputParam;)I");
		if(!m_midRecordedDataIsAvailable)
			break;

		m_midNeedMorePlayData = (env)->GetMethodID(m_cls, "needMorePlayData", "(IBBI[BLcom/voe/common/OutputParam;)I");
		if(!m_midNeedMorePlayData)
			break;

		result = true;

	} while (false);

	return result;
}


int32_t AudioTransportImpl::RecordedDataIsAvailable(const void* audioSamples,
	const uint32_t nSamples,
	const uint8_t nBytesPerSample,
	const uint8_t nChannels,
	const uint32_t samplesPerSec,
	const uint32_t totalDelayMS,
	const int32_t clockDrift,
	const uint32_t currentMicLevel,
	uint32_t& newMicLevel)
{
	int32_t result = 0;
	JNIEnv* env = 0;

	if(before(&env))
	{
		OutputParam param(env);
		jbyteArray array = JniHelper::c2j_bytes(env, (unsigned char*)audioSamples, nSamples * nBytesPerSample);

		result = (env)->CallIntMethod(m_obj, m_midRecordedDataIsAvailable, array, nSamples, nBytesPerSample, nChannels, samplesPerSec,
			totalDelayMS, clockDrift, currentMicLevel, param.getOutput());

		if(result == 0)
		{
			jobject retval = (env)->GetObjectArrayElement(param.getArray(), 0);
			newMicLevel = (uint32_t)JniHelper::j2c_int(env, retval);
		}

		after(env);
	}

	return result;
}

int32_t AudioTransportImpl::NeedMorePlayData(const uint32_t nSamples,
	const uint8_t nBytesPerSample,
	const uint8_t nChannels,
	const uint32_t samplesPerSec,
	void* audioSamples,
	uint32_t& nSamplesOut)
{
	int32_t result = 0;
	JNIEnv* env = 0;

	if(before(&env))
	{
		OutputParam param(env);
		unsigned int size = nSamples * nBytesPerSample;
		jbyteArray array = JniHelper::c2j_bytes(env, 0, size);
		result = (env)->CallIntMethod(m_obj, m_midNeedMorePlayData, nSamples, nBytesPerSample, nChannels, 
			samplesPerSec, array, param.getOutput());
		if(result == 0)
		{
			jobject retval = (env)->GetObjectArrayElement(param.getArray(), 0);
			nSamplesOut = (uint32_t)JniHelper::j2c_int(env, retval);
			JniHelper::j2c_bytes(env, array, (unsigned char*)audioSamples, nSamplesOut);
		}

		after(env);
	}

	return result;
}